package com.alipay.service.listener;

import com.alipay.mapper.RedBagMapper;
import com.alipay.model.dto.TransDto;
import com.alipay.model.entity.RedBagEntity;
import com.alipay.model.enums.RedBagStatusEnum;
import com.alipay.model.enums.RefundStatusEnum;
import com.alipay.service.rpc.TransService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Jun
 * @date 2019/3/23
 * 红包退款延迟队列监听器
 */
@Slf4j
@Service
public class RefundListener {

    @Autowired
    private RedBagMapper redBagMapper;

    @Autowired
    private TransService transService;

    @RabbitListener(queues = "${rabbitmq.refund.queue}")
    protected void onMessage(String redBagNo) {
        RedBagEntity redBagEntity = redBagMapper.getRedBagEntity(redBagNo);
        if (redBagEntity == null || redBagEntity.getStatus().equals(RedBagStatusEnum.FINISHED)){
            return;
        }
        // 设置红包过期
        redBagMapper.updateStatus(redBagNo, RedBagStatusEnum.EXPIRE.getStatus());
        redBagEntity = redBagMapper.getRedBagEntity(redBagNo);

        if (redBagEntity.getAmount().compareTo(redBagEntity.getConsumeAmount()) > 0){
            // 总金额 > 被抢的金额，需要退款
            transService.refund(new TransDto(redBagNo, redBagEntity.getUserId()));
        }else {
            // 无需退款
            redBagMapper.updateRefundStatus(redBagNo, RefundStatusEnum.NOT_NEED.getStatus());
        }

        // TODO 手动提交mq的ack确认，防止消息丢失
    }
}
